<?php
namespace app\admin\controller;
use think\Db;
class Extfield extends Base
{
	public function lists(){
        if( is_post() ){
            $page     = input('page');
            $status   = input('status');
            $keyword  = input('keyword');
            $min_time = input('min_time');
            $max_time = input('max_time');
            
            //原生态sql查询
            $sql = "
                select
                    [1]
                from
                    ext_field
                where 
                    1 = ?
                ";
            $param = [1];
            if ( $status != '100all' ) {
                $sql .= " and status = ?";
                $param[] = $status;
            }
            if ( !empty($keyword) ) {
                $sql .= " and title like ?";
                $param[] = "%{$keyword}%";
            }
            if ( !empty($min_time) ) {
                $sql    .= " and create_time >= ?";
                $param[] = strtotime($min_time);
            }
            if ( !empty($max_time) ) {
                $sql    .= " and create_time <= ?";
                $param[] = strtotime($max_time);
            }
            //总条数
            $sql_count = str_replace("[1]", "count(*) as total", $sql);
            $total     = Db::query($sql_count, $param);
            $total     = $total[0]['total'];
            
            //分页数据
            $page_size   = c('page_size');     #分页条数
            $page        = com_cur_page($total, $page,  $page_size);   #当前页
            $page_data   = com_page_data($total, $page,  $page_size);   #分页原始数据
            
            //列表数据
            $start       = ($page - 1) * $page_size;
            $sql        .= " order by sort desc, id desc limit $start, $page_size";
            $field       = "*";
            $sql_list    = str_replace("[1]", $field, $sql);
            $list        = Db::query($sql_list, $param);

            //格式数据
            foreach($list as $k => $v){                
                $list[$k]['checkbox']       =  com_format_checkbox($v['id']);
                $list[$k]['create_time']    =  com_format_time( $v['create_time'] );
                $list[$k]['sort']           =  com_page( ['url'=>url("c/edit"),'val'=>$v['sort'],'post'=>['t'=>'ext_field','id'=>$v['id'],'f'=>'sort']],'input' );
                $list[$k]['status']         =  com_page( ['url'=>url("c/edit"),'val'=>$v['status'],'post'=>['t'=>'ext_field','id'=>$v['id'],'f'=>'status']],'iphone' );
                $list[$k]['type']           =  c('type.field',$v['type']);
                
                //操作按钮
                $list[$k]['action']          =  com_page(['title'=>'编辑来源','url'=>url("extfield/edit","id={$v['id']}"),'ico'=>'edit','width'=>400,'height'=>300]);
            }
            $com_body    = com_build_table($list, array("id",  "title", "uuid", "type", "long","default","sort","status","create_time", "action"));
            $com_page    = com_build_page( $page_data );
            $data = array(
                "com_body"  => $com_body,
                "com_page"  => $com_page,
            );
            com_check(['data'=>$data,'suc'=>['js_action'=>'function.iphone']]);
        }
        #赋值
        $data = [
            'nav'       => ['来源管理', '列表'],
            'status'    => ['100all'=>'全部状态'] + c('type.status'),
        ];
        return view('', $data);
    }
    
    //添加
    public function add(){
        if( is_post() ){
            $d = com_data(input());
            $rule = [
                'title'      =>  'require',
                'uuid'       =>  'require|alphaDash|unique:ext_field',
                'type'       =>  'require',
                'long'       =>  'number',
            ];
            $msg = [
                'title.require'   =>  '标题不能为空',
            ];
            com_validate( $rule, $msg, $d, true );
            
            if($d['type']!=2 && !$d['long']){
                com_error(['long'=>'非文本类型长度必填!']);
                com_check();
            }
            
            //添加字段
            /*
             * ALTER TABLE `user` ADD COLUMN `telphone`  char(20) NULL DEFAULT '';
             */
            switch ($d['type']){
                case 0:#char
                    if(strlen($d['default'])>$d['long'] || $d['long']<0 || $d['long']>1000){
                        com_error(['long'=>'字段长度配置错误!']);
                        com_check();
                    }else{
                        $sql = "ADD COLUMN `{$d['uuid']}`  char({$d['long']}) NULL DEFAULT '{$d['default']}'"; 
                    }
                    break;
                case 1:#varchar
                    if(strlen($d['default'])>$d['long'] || $d['long']<0 || $d['long']>1000){
                        com_error(['long'=>'字段长度配置错误!']);
                        com_check();
                    }else{
                        $sql = "ADD COLUMN `{$d['uuid']}`  varchar({$d['long']}) NULL DEFAULT '{$d['default']}'"; 
                    }
                    break;
                case 2:#text
                    $sql = "ADD COLUMN `{$d['uuid']}`  text NULL";
                    break;
                case 3:#int
                    $d['default'] = (int)($d['default']);
                    if(strlen($d['default'])>$d['long'] || $d['long']<0 || $d['long']>11){
                        com_error(['long'=>'字段长度配置错误!']);
                        com_check();
                    }else{
                        $sql = "ADD COLUMN `{$d['uuid']}`  int({$d['long']}) NULL DEFAULT {$d['default']}"; 
                    }
                    break;
                case 4:#tinyint
                    $d['default'] = (int)($d['default']);
                    if(strlen($d['default'])>$d['long'] || $d['long']<0 || $d['long']>11){
                        com_error(['long'=>'字段长度配置错误!']);
                        com_check();
                    }else{
                        $sql = "ADD COLUMN `{$d['uuid']}`  tinyint({$d['long']}) NULL DEFAULT {$d['default']}"; 
                    }
                    break;  
            }
            
            Db::query("ALTER TABLE `user` ".$sql);
            Db::query("ALTER TABLE `user_history` ".$sql);
            $d['create_time'] = time();
            Db::name('ext_field')->insert($d);
            
            $config = [
                'suc' => [
                    'msg' => '添加成功！',
                    'js_action' => 'alert|close',
                ],
            ];
            com_check( $config );
        } 
        
        $d = [
            'field' => c('type.field'),
        ];
        return view('', $d);
    }
    
    
    //编辑
    public function edit( $id ){
        if( is_post() ){
            $d = com_data(input());
            $rule = [
                'title'      =>  'require',
            ];
            $msg = [
                'title.require'   =>  '标题不能为空',
            ];
            com_validate( $rule, $msg, $d, true );
            $d['id'] = $id;
            $d['update_time'] = time();
            Db::name('ext_field')->update($d);
            $config = [
                'suc' => [
                    'msg' => '添加成功！',
                    'js_action' => 'alert|close',
                ],
            ];
            com_check( $config );
        }
        $d = [
            'field'     => c('type.field'),
            'info'      => Db::name('ext_field')->find($id),
        ];
        return view('', $d);
    }
}